<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */
namespace lib\lock;


use Svick\Helper\Helper;

class FileLockLib
{
    /**
     * 是否有锁
     *
     * @var boolean
     */
    protected bool $locked = false;

    /**
     * 锁文件资源
     *
     * @var resource
     */
    protected $resource;

    /**
     * 锁名称
     *
     * @var string
     */
    protected string $lockname;

    /**
     * Constructor
     *
     * @param  string $lockname 锁名称
     */
    public function __construct($lockname)
    {
        $this->lockname = $lockname;
    }

    /**
     * Destructor
     *
     * @return void
     */
    public function __destruct()
    {
        $this->unlock();
    }

    /**
     * 获取锁
     *
     * @return boolean
     */
    public function lock()
    {
        if (!$this->locked) {
            $filepath = Helper::path('::/tmp/' . $this->lockname . '.lock');
            $this->resource = @fopen($filepath, 'a');

            if (!$this->resource || !flock($this->resource, LOCK_EX | LOCK_NB)) {
                return false;
            } else {
                $this->locked = true;
            }
        }

        return true;
    }

    /**
     * 释放锁
     *
     * @return bool
     */
    public function unlock()
    {
        if (!$this->locked) {
            return false;
        }

        flock($this->resource, LOCK_UN);
        fclose($this->resource);

        $this->resource = null;
        $this->locked = false;

        return true;
    }
}
